package me.boot.db.mybatis.datasource;

import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.support.DdConstants;
import lombok.extern.slf4j.Slf4j;
import me.boot.db.mybatis.propertites.BasicDataSourceProperties;
import me.boot.db.mybatis.propertites.DbProperties;
import me.boot.db.mybatis.propertites.TenantMode;
import org.springframework.beans.BeanUtils;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 从主数据源中获取其它动态数据源的配置信息
 */
@Slf4j
public class TenantDataSourceProvider extends AbstractDataSourceProvider implements DynamicDataSourceProvider {
    private BasicDataSourceProperties dataSourceProperties;
    private DbProperties dbProperties;
    private TenantDataSourceLoader loader;

    public TenantDataSourceProvider(BasicDataSourceProperties dataSourceProperties, DbProperties dbProperties, TenantDataSourceLoader loader) {
        this.dataSourceProperties = dataSourceProperties;
        this.dbProperties = dbProperties;
        this.loader = loader;
    }

    @Override
    public Map<String, DataSource> loadDataSources() {
        Map<String, DataSourceProperty> map = new HashMap<>(8);

        if (dataSourceProperties != null) {
            DataSourceProperty master = from(dataSourceProperties);
            DataSourceProperty property = convert(master);
            map.put(DdConstants.MASTER, property);
        }

        //租户独立数据源模式
        if (dbProperties.getTenant().getMode().equals(TenantMode.DATASOURCE) && loader != null) {
            loader.load().forEach(p -> {
                DataSourceProperty property = convert(p);
                map.put(property.getPoolName(), property);
            });
        }
        return createDataSourceMap(map);
    }

    DataSourceProperty from(BasicDataSourceProperties dataSourceProperties) {
        DataSourceProperty property = new DataSourceProperty();
        BeanUtils.copyProperties(dataSourceProperties, property);
        return property;
    }

    DataSourceProperty convert(DataSourceProperty raw) {
        DataSourceProperty property = new DataSourceProperty();
        BeanUtils.copyProperties(raw, property);
        globalSet(property);
        return property;
    }

    void globalSet(DataSourceProperty p) {
//        p.setLazy(true);
//        p.setP6spy(false);
//        p.setSeata(dbProperties.getTransaction().isSeata());
    }
}
